import axios from 'axios';
import {
  Message
} from 'element-ui';

export default {
  state: {
    count: 0,
    ajaxApi: '/',
    // ajaxApi: 'http://192.168.1.150:9000/',
    // ajaxApi: '192.168.1.179:9880/',
    env: process.env.NODE_ENV,
    linkAttr: [],
    serialNumber: '',
    pushData: [],
    mainPage: null,
    globalVariable: {},

    globalCountrySetting: [], //国家配置
    /* new start */
    leftModeCharts: {
      IsShow: true,
    },
    rightModeCharts: {
      IsShow: true,
    },
    //地图设置
    centralModeMapSetting: {
      isShow: true,
      nowCountry: {},
    },
    //地图弹框
    bottomModeMapView: {
      IsShow: false,
      IsIconShow: false,
      checkedlist: [],
      checkedIDlist: [],
      checkedSpeciallist: [],
      checkedLIDlist: [],
      nodeNum: 0,
      lineNum: 0,
    },
    /* new end */
  },
  getters: {
    globalCountrySetting: (state) => state.globalCountrySetting,
    bottomModeMapView: (state) => state.bottomModeMapView,
    bottomIconMapView: (state) => state.bottomIconMapView,
    centralModeMapSetting: (state) => state.centralModeMapSetting,
  },
  mutations: {
    increment(state) {
      state.count++
    },
    changeCountry(state, obj) {
      state.globalCountrySetting = obj;
    },
    /* 地图设置 start */
    changeMapSettingIs(state, isShow) {
      state.centralModeMapSetting.isShow = isShow;
    },
    changeMapSettingData(state, data) {
      state.centralModeMapSetting.nowCountry = data;
    },
    /* 地图设置 end */
    /* 基地操作 start */
    //打开弹框
    OPENWindowBase(state, data) {
      // console.log(data)
      if (data.type === "base") {
        state.bottomModeMapView.IsShow = data.isOpen;
        if (data.isOpen) {
          state.bottomModeMapView.IsIconShow = false;
        }
      } else {
        state.bottomModeMapView.IsIconShow = data.isOpen;
        if (data.isOpen) {
          state.bottomModeMapView.IsShow = false;
        }
      }
    },
    //添加--普通
    changeBaseChecked(state, data) {
      state.bottomModeMapView.checkedlist.push(data);
      state.bottomModeMapView.checkedIDlist.push(data.id);
    },
    //删除--普通
    deleteBaseChecked(state, index) {
      state.bottomModeMapView.checkedlist.splice(index, 1);
      state.bottomModeMapView.checkedIDlist.splice(index, 1);
    },
    //添加--特殊
    changeBaseCheckedSpcial(state, data) {
      state.bottomModeMapView.checkedSpeciallist.push(data);
      state.bottomModeMapView.checkedLIDlist.push(data.id);
    },
    //删除--特殊
    deleteBaseCheckedSpcial(state, index) {
      state.bottomModeMapView.checkedSpeciallist.splice(index, 1);
      state.bottomModeMapView.checkedLIDlist.splice(index, 1);
    },

    //修改数据总量
    changeDataNum(state, data) {
        state.bottomModeMapView.nodeNum = data.nodeNum;
        state.bottomModeMapView.lineNum = data.lineNum;
      },
    /* 基地操作 end */
  },
  actions: {
    // 封装一个 ajax 方法
    ajax(context, {
      url,
      data,
      method,
      succeed,
      errored,
    }) {
      if (url.substr(0, 6) === 'local:') {
        url = (context.state.env === 'production' ? './' : '') + url.substr(6);
      } else {
        url = context.state.ajaxApi + url;
      }
      axios({
        url: url,
        method: method || 'get',
        params: (method || 'get') === 'get' ? data : {},
        headers: {
          'token': sessionStorage.token
        },
        data: data || {}
      }).then(function (res) {
        if (res.data.code && res.data.code.toString() !== '200') {
          Message({
            type: 'warning',
            showClose: true,
            message: res.data.message,
          });
          return false;
        }

        if (succeed && typeof succeed === 'function') {
          succeed(res.data);
        }
      }).catch(function (error) {
        // console.log(error);
        // console.log(error.response);
        errored(error)
        if (error.response) {
          const status = error.response.status;
          Message({
            type: 'error',
            showClose: true,
            message: '请求失败',
          });
          if (status === 401) {
            window.location.href = window.location.href = context.state.env === 'production' ? './' : '/#login';
          }
        }
      });
    },
    ajaxApi(context, {
      url,
      data,
      method,
      succeed
    }) {
      if (context.state.env === 'production') {
        url;
      } else {
        url = '/api' + url;
      }


      axios({
        url: url,
        method: method || 'get',
        params: (method || 'get') == 'get' ? data : {},
        headers: {
          'token': sessionStorage.token
        },
        data: data || {}
      }).then(function (res) {
        console.log(res)
        if (res.data.code && res.data.code.toString() !== '200') {
          Message({
            type: 'warning',
            showClose: true,
            message: res.data.message,
          });
          return false;
        }

        if (succeed && typeof succeed == 'function') {
          succeed(res.data);
        }
      }).catch((error) => {
        console.log(error);

        if (error.response) {
          const status = error.response.status;
          if (status === 401) {
            window.location.href = context.state.env === 'production' ? './#/login' : '/#/login';
          } else if (status === 402) {
            const h = this._vm.$createElement;
            Notification({
              title: '授权提醒',
              duration: 0,
              dangerouslyUseHTMLString: true,
              message: h('span', null, [
                h('span', null, '授权已过期，请重新'),
                h('a', {
                  style: 'color: #3579f8',
                  attrs: {
                    href: 'javascript:;'
                  },
                  on: {
                    click: this._actions.authImport
                  }
                }, '导入授权')
              ])
            });
          }
        } else {
          Message({
            type: 'error',
            showClose: true,
            message: '请求失败'
          });
        }
      });
    },
    // 封装一个 ajax 方法
    ajaxAll(context, {
      url,
      data,
      method,
      succeed
    }) {
      if (url.substr(0, 6) === 'local:') {
        url = (context.state.env === 'production' ? './' : '') + url.substr(6);
      } else {
        url = context.state.ajaxApi + url;
      }
      axios({
        url: url,
        method: method || 'get',
        params: (method || 'get') === 'get' ? data : {},
        headers: {
          'token': sessionStorage.token
        },
        data: data || {}
      }).then(function (res) {
        if (res.data.code && res.data.code.toString() !== '200') {
          Message({
            type: 'warning',
            showClose: true,
            message: res.data.message,
          });
          return false;
        }

        if (succeed && typeof succeed === 'function') {
          succeed(res);
        }
      }).catch(function (error) {
        console.log(error);

        if (error.response) {
          const status = error.response.status;
          Message({
            type: 'error',
            showClose: true,
            message: '请求失败',
          });
          if (status === 401) {
            window.location.href = window.location.href = context.state.env === 'production' ? './' : '/#login';
          }
        }
      });
    },
    defaultNzmodatl(o) {
      console.log(o)
      let detailHtml = '';
      let title = o.title !== undefined ? o.title : '',
        parameter = o.parameter !== undefined ? o.parameter : '',
        html = o.html !== undefined ? o.html : '',
        serNum = o.serNum !== undefined ? o.serNum : '';

      detailHtml += (function () {
        let str = '';
        let style = '';
        if (parameter) {
          for (let i in parameter) {
            style += `${i}: ${parameter[i]};`;
          }
          str = `<div class="ps_dialog animated zoomInLeft" style="${style}">`;
        } else {
          str = `<div class="ps_dialog animated zoomInLeft">`;
        }
        return str;
      })();
      detailHtml += `<div class="ps-dialog-head"><span class="ps-dialog-title">${title}</span><span class="ps-dialog-close close" onclick="mainVue.$store.dispatch('deletePopup',{parameter: ${serNum}})"></span>`;
      // return;
      detailHtml += `</div>
                      <div class="ps-dialog-body">${html}</div>
                      <div class="ps-dialog-foot"></div>
                      <!--</div>-->`;
      return detailHtml;
    },
    getMainVue(context) {
      console.log('awsl')
      const globalVariable = context.state.globalVariable;
      const mainPage = context.state.mainPage;
      if (globalVariable['countryList']) {
        for (const i in mainPage.pointObj) {
          mainPage.deletePoinobj(i);
        }
        globalVariable['countryList'].zTreeTools = globalVariable['countryList'].zTreeTools === 'list' ? 'ship' : 'list';
        let zTreeTools = globalVariable['countryList'].zTreeTools;
        globalVariable['countryList'].create_tree(zTreeTools);
      }
    },
    deletePopup(context, {
      parameter
    }) {
      const mainPage = context.state.mainPage;
      mainPage.deletePopup(parameter);
    },
    //改变国家配置
    changeCountry({
      commit
    }, obj) {
      return commit('changeCountry', obj)
    },
    //改变勾选基地
    changeBaseChecked({
      commit
    }, data) {
      return commit('changeBaseChecked', data)
    },
    //删除基地
    deleteBaseChecked({
      commit
    }, index) {
      return commit('deleteBaseChecked', index)
    },
    //打开基地弹框
    OpenWindowBase({
      commit
    }, isShow, type) {
      return commit('OPENWindowBase', isShow, type)
    },
  }
}